﻿using DBServer.Selenium.Extenium.Exception;
using DBServer.Selenium.Extenium.Path;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Selenium;

namespace DBServer.Selenium.Extenium.Fixtures
{
    public class MenuFixture : ExtComponentFixture
    {
        public MenuFixture(ISelenium driver, string name) : base(driver, new ExtComponentPath(name))
        {
        }

        protected MenuFixture(ISelenium driver, IPath path) : base(driver, path)
        {
        }

        public MenuFixture RequireItem(string label)
        {
            ItemIndex(label);
            return this;
        }

        public MenuItemFixture Item(int index)
        {
            return new MenuItemFixture(Driver, Path.Eval() + ".items.items[" + index + "]");
        }

        public MenuItemFixture Item(string label)
        {
            return Item(ItemIndex(label));
        }

        private int ItemIndex(string label)
        {
            for (var i = 0; i < ItemCount(); i++)
            {
                var title = ItemTitle(i);
                var text = ItemText(i);
                if (label == title || label == text)
                    return i;
            }
            throw new ExteniumException("Item not found: " + label);
        }

        private string ItemTitle(int index)
        {
            return SafeExec(Path.Eval() + ".items.items[" + index + "].title");
        }

        private string ItemText(int index)
        {
            return SafeExec(Path.Eval() + ".items.items[" + index + "].text");
        }

        private int ItemCount()
        {
            var eval = SafeExec(Path.Eval() + ".items.items.length");
            return int.Parse(eval);
        }
    }
}
